﻿using System;
using System.Collections.Generic;

namespace ComputedTable.Version10
{
    public class CalculatorFactory<TRowId, TColumnId, TOperationContext> : ICalculatorFactory<TRowId, TColumnId, TOperationContext> 
        where TOperationContext : IOperationContext<TRowId, TColumnId>
    {
        private Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>();

        public void Register<TDefinition, TCalculator>() where TCalculator : ICalculator<TOperationContext>, new()
        {
            this.dictionary[typeof(TDefinition)] = typeof(TCalculator);
        }

        public ICalculator<TOperationContext> Resolve<TDefinition>()
        {
            Type definitionType = typeof(TDefinition);
            bool found = this.dictionary.ContainsKey(definitionType);
            if (!found)
            {
                string message = string.Format("Cannot resolve type '{0}'", definitionType.Name);
                throw new KeyNotFoundException(message);
            }

            Type calculatorType = this.dictionary[definitionType];
            var calculator = (ICalculator<TOperationContext>)Activator.CreateInstance(calculatorType);
            return calculator;
        }
    }
}
